/**
 * Created by MyPC on 2017/7/23.
 */
var express = require('express');
var router = express.Router();
let logger = require('log4js').getLogger('postRoutes');
let PostModel = require('../../schemas/post');
let TagModel = require('../../schemas/tag');
let CategoryModel = require('../../schemas/category');

let response = require('../../common/responseJson');
let Snowflake = require('node-snowflake').Snowflake;

let pageUtil = require('../../utils/pageUtil');

router.get('/', function (req, res, next) {
  let params = {};    // 查詢條件
  let id = req.query.id;      // ID 查詢
  if(id){
    params['_id'] = id;
  }
  let title = req.query.title;
  if(title){
    let regexp = RegExp('/'+title+'/i');
    params['title'] = {'$regex': regexp}
  }
  let alias = req.query.alias;
  if(alias){
    params['alias'] = alias;
  }
  let categoryId = req.query.categoryId;
  if(categoryId){
    params['categoryId'] = categoryId;
  }
  let labels = req.query.labels;
  if(labels){
    labels = labels.split(',');
    params['labels'] = {'$all': labels};
  }
  let startTime = req.query.startTime;    // 起始時間
  if(startTime){
    params['createTime'] = {
      '$gte': moment(startTime)
    };
  }
  let endTime = req.query.endTime;      // 結束時間
  if(endTime){
    params['createTime'] = {
      '$lte': moment(endTime)
    };
  }
 /* let status = Number(req.query.status);
  if(status !== undefined){
    if(status==='0'){    // 查詢全部
      params['deleteTime'] = {'$ne': null};
    }else{
      params['deleteTime'] = {'$eq': null};
    }
  }*/
  params['deleteTime'] = {'$eq': null};
  let page = Number(req.query.page);
  let pageSize = Number(req.query.pageSize);
  pageUtil(PostModel, {
    'query': params,
    'page': page,
    'pageSize': pageSize,
    'column': {
      '_id': 0,
      'title': 1,
      'alias': 1,
      'url': 1,
      'source': 1,
      'categoryId': 1,
      'labels': 1,
      'viewCount': 1,
      'isSecret': 1,
      'createTime': 1,
      'updateTime': 1,
    },
    'sort': {
      'createTime': -1
    },
    'populate': {
      path: 'categoryId',
      select: {
        '_id': 1,
        'cateName': 1
      }
    }
  }).then((result)=> {
    response.success(res, result);
  }).catch((err)=> {
    logger.error('查詢用戶報錯,kcId:%s, error:%s', kcId, err)
    response.fail(res, err);
  });
});

router.post('/', function (req, res, next) {
  let title = req.body.title;
  let alias = Snowflake.nextId();
  let summary = req.body.summary;
  let source = req.body.source;
  let content = req.body.content;
  let categoryId = req.body.categoryId;
  let labels = req.body.labels;
  let url = req.body.url;                   //
  let isSecret = Boolean(req.body.isSecret);         //
  let isDraft = Boolean(req.body.isDraft);   //是否是草稿
  if(!title){
    response.fail(res, '标题不能为空');
    return;
  }
  if(summary && summary.length>250){
    response.fail(res, '摘要最多250个字符');
    return;
  }
  if(!categoryId){
    response.fail(res, '文章主题不能为空');
    return;
  }
  let query = CategoryModel.findById(categoryId);
  query.then(function (result) {
    if(!result){
      return Promise.reject('文章主题不存在');
    }else{
      if(result.isSecret){
        isSecret = true;
      }
      let addParam = {
        'title':title,
        'alias': alias,
        'summary': summary,
        'source': source,
        'content': content,
        'categoryId': categoryId,
        'labels': labels,
        'url': url,
        'isSecret': isSecret,
        'isDraft': isDraft
      };
      return PostModel.create(addParam);
    }
  }).then(function (result) {
    labels.forEach(function (item, index) {
      TagModel.findOne({'names': item}).then((result)=>{
        if(result){
          return TagModel.update({'_id': result['_doc']['_id']}, {'$inc': {'num': 1}});
        }else{
          return TagModel.create({'names': item});
        }
      }).then((result)=> {

      }).catch((err)=> {
        logger.error('操作标签出错,标签名:%s, error:%s', item, err);
      });
    });
    response.success(res, result);
  }).catch(function (err) {
    response.fail(res, err);
  });
});

router.get('/:id', function (req, res, next) {
  let id = req.params.id;
  PostModel.findOne({'alias':id}).then((result)=>{
    response.success(res, result);
    PostModel.update({'alias':id}, {$inc: {'viewCount': 1}}).then((result)=>{

    }).catch((err)=> {
      console.error(err);
    })
  }).catch((err)=> {
    response.fail(res, err);
  });
});

router.put('/:id', function (req, res, next) {
  let id = req.params.id;
  let title = req.body.title;
  let summary = req.body.summary;
  let source = req.body.source;
  let content = req.body.content;
  let categoryId = req.body.categoryId;
  let oldCategoryId = null;
  let labels = req.body.labels;
  let oldLabels = null;
  let url = req.body.url;                   //
  let isSecret = Boolean(req.body.isSecret);         //
  let isDraft = Boolean(req.body.isDraft);   //是否是草稿
  if(!title){
    response.fail(res, '标题不能为空');
    return;
  }
  if(summary && summary.length>250){
    response.fail(res, '摘要最多250个字符');
    return;
  }
  if(!categoryId){
    response.fail(res, '文章主题不能为空');
    return;
  }
  PostModel.findOne({'alias':id}).then((result)=>{
    oldLabels = result['_doc']['labels'];
    oldCategoryId = result['_doc']['categoryId'];
    return CategoryModel.findById(categoryId);
  }).then(function (result) {
    if(!result){
      return Promise.reject('文章主题不存在');
    }else{
      if(result.isSecret){
        isSecret = true;
      }
      let addParam = {
        'title':title,
        'summary': summary,
        'source': source,
        'content': content,
        'categoryId': categoryId,
        'labels': labels,
        'url': url,
        'isSecret': isSecret,
        'isDraft': isDraft
      };
      return PostModel.update({'alias': id}, {'$set': addParam});
    }
  }).then(function (result) {
    // 如果以前不存在,现在存在,则新增标签,或者标签数量加一
    labels.forEach(function (item, index) {
      let indexof = oldLabels.indexOf(item);
      if(indexof===-1){    // 标签名以前不存在在文章
        console.log('indexof===-1:', item);
        TagModel.findOne({'names': item}).then((result)=>{
          if(result){
            return TagModel.update({'_id': result['_doc']['_id']}, {'$inc': {'num': 1}});
          }else{
            return TagModel.create({'names': item});
          }
        }).then((result)=> {

        }).catch((err)=> {
          logger.error('操作标签出错,标签名:%s, error:%s', item, err);
        });
      }else{
        oldLabels.splice(indexof, 1);
      }
    });
    // 如果以前存在,现在不存在,标签文章数量减一
    oldLabels.forEach((item, index)=> {
      TagModel.update({'names': item}, {'$inc': {'num': -1}}).then((result)=> {

      }).catch((err)=> {
        logger.error('操作标签出错,标签名:%s, error:%s', JSON.stringify(item), err);
      });
    });
    response.success(res, result);
  }).catch(function (err) {
    logger.error(err);
    response.fail(res, err);
  });
});

router.delete('/:id', function (req, res, next) {
  let id = req.params.id;
  let promise = PostModel.findOneAndUpdate({'alias': id}, {'deleteTime': new Date()});
  promise.then(function(result){
    result['_doc']['labels'].forEach((item)=>{
      TagModel.update({'names': item}, {'$inc': {'num': -1}}).then((result)=> {

      }).catch((err)=> {
        logger.error('操作标签出错,标签名:%s, error:%s', JSON.stringify(item), err);
      });
    });
    response.success(res, result);
  }).catch(function (err) {
    logger.error('删除文章出错,id:%s, error:%s', id, err);
    response.error(res);
  });
});











module.exports = router;
